package com.minghe

import jakarta.enterprise.context.ApplicationScoped
import jakarta.inject.Inject
import jakarta.persistence.EntityManager
import jakarta.persistence.NoResultException
import jakarta.persistence.NonUniqueResultException
import jakarta.transaction.Transactional
import java.time.Instant

//
//
//@ApplicationScoped
//class Init_StockRepository : Serializable{
//
//    @Inject
//    lateinit var entityManager: EntityManager
//
//    fun findSummary(
//        storeCode: Int,
//        productCode: String,
//        stockDate: Instant
//    ): StockSumDTO? {
//        return try {
//            entityManager.createNativeQuery(
//                """
//                SELECT
//                    stock_date as stock_date,
//                    store_code as store_code,
//                    product_code as product_code,
//                    SUM(quantity) as quantity
//                FROM init_stock
//                WHERE store_code = ?1
//                AND product_code = ?2
//                AND stock_date = ?3
//                GROUP BY
//                stock_date, store_code, product_code
//                """,
//                "StockSumDTOMapping"
//            )
//                .setParameter(1, storeCode)
//                .setParameter(2, productCode)
//                .setParameter(3, stockDate)
//                .resultList
//                .firstOrNull() as? StockSumDTO
//        } catch (e: Exception) {
//            throw RuntimeException("Query failed", e)
//        }
//    }
//
//}

@ApplicationScoped
class Init_StockRepository {

    @Inject
    lateinit var entityManager: EntityManager

    @Transactional
    fun findSummary(
        storeCode: Int,
        productCode: String,
        stockDate: Instant
    ): StockSumDTO? {
        val query = entityManager.createNativeQuery(
            """
            SELECT 
                stock_date,
                store_code,
                product_code,
                SUM(quantity) as quantity
            FROM init_stock
            WHERE store_code = ?1
                AND product_code = ?2
                AND stock_date = ?3
            GROUP BY stock_date, store_code, product_code
            """,
            "StockSumDTOMapping"
        ).apply {
            setParameter(1, storeCode)
            setParameter(2, productCode)
            setParameter(3, stockDate)
        }

        return try {
            query.singleResult as StockSumDTO
        } catch (e: NoResultException) {
            null // 明确返回 null 表示无结果
        } catch (e: NonUniqueResultException) {
            throw RuntimeException("Multiple results found", e)
        }
    }
}